import os
import sqlite3

class LocalDBManager:
    def __init__(self, logger, db_path="cookies/appdata.db"):
        self.logger = logger
        self.db_path = db_path
        self.conn = None
        self.cursor = None
        self._connect()
        self._create_tables()

    def _connect(self):
        try:
            os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
            self.conn = sqlite3.connect(self.db_path)
            self.cursor = self.conn.cursor()
        except Exception as e:
            self.logger.exception("数据库连接失败", exc_info=e)

    def _create_tables(self):
        try:
            # 创建 stores 表
            self.cursor.execute(f'''
                CREATE TABLE IF NOT EXISTS stores_data (
                    store_name TEXT PRIMARY KEY,
                    username TEXT,
                    password TEXT
                )
            ''')
            self.conn.commit()
        except Exception as e:
            self.logger.exception("数据表创建失败", exc_info=e)
    def insert_or_update_store(self, store_name, username, password):
        try:
            self.cursor.execute(f'''
                INSERT OR REPLACE INTO stores_data (store_name, username, password)
                VALUES (?, ?, ?)
            ''', (store_name, username, password))
            self.conn.commit()
            self.logger.info(f"店铺登录数据数据已更新: {store_name}")
        except Exception as e:
            self.logger.exception(f"更新店铺登录数据失败: {store_name}", exc_info=e)

    def get_all_stores_dict(self):
        try:
            sql = f"SELECT store_name, username, password FROM stores_data"
            params = []
            sql += " ORDER BY store_name ASC"

            self.cursor.execute(sql, params)
            rows = self.cursor.fetchall()
            return [dict(zip(['store_name', 'username', 'password'], r)) for r in rows]
        except Exception as e:
            self.logger.exception("查询店铺失败", exc_info=e)
            return []
    def close(self):
        if self.conn:
            self.conn.close()